{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://www.bigdatauniversity.com\"><img src = \"https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png\" width = 300, align = \"center\"></a>\n",
    "\n",
    "<h1 align=center><font size = 5>Lab: Connect to Db2 database on Cloud using Python</font></h1>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "\n",
    "This notebook illustrates how to access a DB2 database on Cloud using Python by following the steps below:\n",
    "1. Import the `ibm_db` Python library\n",
    "1. Enter the database connection credentials\n",
    "1. Create the database connection\n",
    "1. Close the database connection\n",
    "\n",
    "\n",
    "\n",
    "__Note:__ Please follow the instructions given in the first Lab of this course to Create a database service instance of Db2 on Cloud and retrieve your database Service Credentials.\n",
    "\n",
    "## Import the `ibm_db` Python library\n",
    "\n",
    "The `ibm_db` [API ](https://pypi.python.org/pypi/ibm_db/) provides a variety of useful Python functions for accessing and manipulating data in an IBM® data server database, including functions for connecting to a database, preparing and issuing SQL statements, fetching rows from result sets, calling stored procedures, committing and rolling back transactions, handling errors, and retrieving metadata.\n",
    "\n",
    "\n",
    "We first import the ibm_db library into our Python Application\n",
    "\n",
    "Execute the following cell by clicking within it and then \n",
    "press `Shift` and `Enter` keys simultaneously\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import ibm_db"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the command above completes, the `ibm_db` library is loaded in your notebook. \n",
    "\n",
    "\n",
    "## Identify the database connection credentials\n",
    "\n",
    "Connecting to dashDB or DB2 database requires the following information:\n",
    "* Driver Name\n",
    "* Database name \n",
    "* Host DNS name or IP address \n",
    "* Host port\n",
    "* Connection protocol\n",
    "* User ID (or username)\n",
    "* User Password\n",
    "\n",
    "\n",
    "\n",
    "__Notice:__ To obtain credentials please refer to the instructions given in the first Lab of this course\n",
    "\n",
    "Now enter your database credentials below and execute the cell with `Shift` + `Enter`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Replace the placeholder values with your actual Db2 hostname, username, and password:\n",
    "dsn_hostname = \"YourDb2Hostname\" # e.g.: \"dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net\"\n",
    "dsn_uid = \"YourDb2Username\"        # e.g. \"abc12345\"\n",
    "dsn_pwd = \"YoueDb2Password\"      # e.g. \"7dBZ3wWt9XN6$o0J\"\n",
    "\n",
    "dsn_driver = \"{IBM DB2 ODBC DRIVER}\"\n",
    "dsn_database = \"BLUDB\"            # e.g. \"BLUDB\"\n",
    "dsn_port = \"50000\"                # e.g. \"50000\" \n",
    "dsn_protocol = \"TCPIP\"            # i.e. \"TCPIP\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create the DB2 database connection\n",
    "\n",
    "Ibm_db API uses the IBM Data Server Driver for ODBC and CLI APIs to connect to IBM DB2 and Informix.\n",
    "\n",
    "\n",
    "Lets build the dsn connection string using the credentials you entered above\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#DO NOT MODIFY THIS CELL. Just RUN it with Shift + Enter\n",
    "#Create the dsn connection string\n",
    "dsn = (\n",
    "    \"DRIVER={0};\"\n",
    "    \"DATABASE={1};\"\n",
    "    \"HOSTNAME={2};\"\n",
    "    \"PORT={3};\"\n",
    "    \"PROTOCOL={4};\"\n",
    "    \"UID={5};\"\n",
    "    \"PWD={6};\").format(dsn_driver, dsn_database, dsn_hostname, dsn_port, dsn_protocol, dsn_uid, dsn_pwd)\n",
    "\n",
    "#print the connection string to check correct values are specified\n",
    "print(dsn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now establish the connection to the database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#DO NOT MODIFY THIS CELL. Just RUN it with Shift + Enter\n",
    "#Create database connection\n",
    "\n",
    "try:\n",
    "    conn = ibm_db.connect(dsn, \"\", \"\")\n",
    "    print (\"Connected to database: \", dsn_database, \"as user: \", dsn_uid, \"on host: \", dsn_hostname)\n",
    "\n",
    "except:\n",
    "    print (\"Unable to connect: \", ibm_db.conn_errormsg() )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Congratulations if you were able to connect successfuly. Otherwise check the error and try again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Retrieve Metadata for the Database Server\n",
    "server = ibm_db.server_info(conn)\n",
    "\n",
    "print (\"DBMS_NAME: \", server.DBMS_NAME)\n",
    "print (\"DBMS_VER:  \", server.DBMS_VER)\n",
    "print (\"DB_NAME:   \", server.DB_NAME)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#Retrieve Metadata for the Database Client / Driver\n",
    "client = ibm_db.client_info(conn)\n",
    "\n",
    "print (\"DRIVER_NAME:          \", client.DRIVER_NAME) \n",
    "print (\"DRIVER_VER:           \", client.DRIVER_VER)\n",
    "print (\"DATA_SOURCE_NAME:     \", client.DATA_SOURCE_NAME)\n",
    "print (\"DRIVER_ODBC_VER:      \", client.DRIVER_ODBC_VER)\n",
    "print (\"ODBC_VER:             \", client.ODBC_VER)\n",
    "print (\"ODBC_SQL_CONFORMANCE: \", client.ODBC_SQL_CONFORMANCE)\n",
    "print (\"APPL_CODEPAGE:        \", client.APPL_CODEPAGE)\n",
    "print (\"CONN_CODEPAGE:        \", client.CONN_CODEPAGE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Close the Connection\n",
    "We free all resources by closing the connection. Remember that it is always important to close connections so that we can avoid unused connections taking up resources."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ibm_db.close(conn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "In this tutorial you established a connection to a DB2 database on Cloud database from a Python notebook using ibm_db API. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright &copy; 2017 [cognitiveclass.ai](cognitiveclass.ai?utm_source=bducopyrightlink&utm_medium=dswb&utm_campaign=bdu). This notebook and its source code are released under the terms of the [MIT License](https://bigdatauniversity.com/mit-license/).\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "widgets": {
   "state": {},
   "version": "1.1.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
